package com.jxwifi.cloud.quickclean.order;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.RouteSearch;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.idroid.utils.NoDoubleClickListener;
import com.idroid.utils.TextDrawable;
import com.idroid.widget.LoadDialog;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.adapter.CleanerListAdapter;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.MyCleanersBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.utils.ShareCleanerDialog;
import com.view.SuperSwipeRefreshLayout;

import java.util.List;

public class MyCleanerPresenter {

    private String TAG = this.getClass().getSimpleName();
    private Context mContext;
    private MyCleanerView mView;
    private AuzImpl mAuz;
    private int mPageIndex = 1;
    private int mCurrentCounter;//获取的数据个数
    private boolean mNoData = true;
    private CleanerListAdapter mAdapter;
    private boolean isErr = true;
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）
    public List<MyCleanersBean> mrecords;
    public List<MyCleanersBean> mrecordsFilter;

    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    public boolean isSearch = false;
    public ShareCleanerDialog dialogshow;
    public LoadDialog mLoadDialog;//加载动画

    public MyCleanerPresenter(Context context, MyCleanerView view) {
        this.mContext = context;
        this.mView = view;
        this.mAuz = new AuzImpl();
    }

    public void Refresh(final boolean isCollection) {
        mAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) mView.getRView().getParent());
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mNoData) {
                    mPageIndex = 1;
                    isSearch = false;
                    if(isCollection){
                        getCollectionCleanerData();
                    }else{
                        getData();
                    }
                } else {
                    mAdapter.setEmptyView(mView.getViews());
                }
            }
        }, 1000);
    }

    public void getData() {
        Params params = new Params();
        params.add("limit", mView.getLimit());
        params.add("orderCode", mView.getOrderCode());
        params.add("page", mPageIndex);
        params.add("serviceTime", mView.getServiceTime());
        mAuz.auzpost(UrlPool.ORDER_MY_CLEANERS, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    String str = obj.getString("records");
                    mTotalNum = obj.getInteger("total");
                    mrecords = JSON.parseArray(str, MyCleanersBean.class);

                    //计算骑行距离
                    //for (int i = 0; i < mrecords.size(); i++) {
                        Log.i(TAG,"onRideRouteSearched ==>0 保洁员：" + mrecords.get(0).getRealName()+"mrecords.size() = "+mrecords.size());
                        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                                new LatLonPoint(Double.valueOf(StateUtils.AddLat), Double.valueOf(StateUtils.AddLon)),
                                new LatLonPoint(Double.valueOf(mrecords.get(0).getLat()), Double.valueOf(mrecords.get(0).getLon())));
                        RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(
                                fromAndTo, RouteSearch.RidingDefault);
                        mView.getRouteSearch().calculateRideRouteAsyn(query);
                    //}

                    /*if (mPageIndex == 1) {
                        setData(true, mrecords,true);
                    } else {
                        setData(false, mrecords,true);
                    }*/
                } else {
                    mView.onData();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                isErr = false;
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void setRideData(int position){

        if (isSearch){
            if (position<mrecordsFilter.size()){
                RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                        new LatLonPoint(Double.valueOf(StateUtils.AddLat), Double.valueOf(StateUtils.AddLon)),
                        new LatLonPoint(Double.valueOf(mrecordsFilter.get(position).getLat()), Double.valueOf(mrecordsFilter.get(position).getLon())));
                RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(
                        fromAndTo, RouteSearch.RIDING_DEFAULT);
                mView.getRouteSearch().calculateRideRouteAsyn(query);
            }else{
                setData(true, mrecordsFilter,false);
            }

        }else{
            if(position < mrecords.size()){
                Log.i(TAG,"onRideRouteSearched ==> "+position+" 保洁员：" + mrecords.get(position).getRealName()+"位置 = "+mrecords.get(position).getAddress());
                RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                        new LatLonPoint(Double.valueOf(StateUtils.AddLat), Double.valueOf(StateUtils.AddLon)),
                        new LatLonPoint(Double.valueOf(mrecords.get(position).getLat()), Double.valueOf(mrecords.get(position).getLon())));
                RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(
                        fromAndTo, RouteSearch.RidingDefault);
                mView.getRouteSearch().calculateRideRouteAsyn(query);
            }else {
                Log.i(TAG,"onRideRouteSearched ==>  setData ");
                if (mPageIndex == 1) {
                    setData(true, mrecords,true);
                } else {
                    setData(false, mrecords,true);
                }
            }

        }

    }

    public void onDataList(final boolean isCollection) {
        mView.getRView().setLayoutManager(new LinearLayoutManager(mContext));
        if (isCollection){
            mAdapter = new CleanerListAdapter(R.layout.list_cleaner_item,mrecordsFilter,isCollection);
        }else{
            mAdapter = new CleanerListAdapter(R.layout.list_cleaner_item,mrecords,isCollection);
        }
        mView.getRView().setAdapter(mAdapter);
        mAdapter.openLoadAnimation();
        mAdapter.openLoadAnimation(BaseQuickAdapter.FOOTER_VIEW);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.rel_list_cleaner_items:
                        if (StateUtils.TRUE.equals(mAdapter.getData().get(position).getIsInDispatch())){
                            mView.onClickCleaning(mAdapter.getData().get(position));
                        }
                        break;
                    case R.id.img_collection_my_cleaner:
                        CancelCollectionCleaner(position);
                        break;
                    case R.id.img_share_cleaner:
                        shareDialog(position);
                        break;
                }
            }
        });
        //上拉加载更多操作
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mView.getRView().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentCounter >= mTotalNum) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                        } else {
                            if (isErr) {
                                isSearch = false;
                                if(isCollection){
                                    getCollectionCleanerData();
                                }else{
                                    getData();
                                }
                                //成功获取更多数据
                                mCurrentCounter = mAdapter.getData().size();
                                mAdapter.loadMoreComplete();
                            } else {
                                //获取更多数据失败
                                isErr = true;
                                Toast.makeText(mContext, "获取更多数据失败", Toast.LENGTH_LONG).show();
                                mAdapter.loadMoreFail();
                            }
                        }
                    }
                }, 1500);

            }
        }, mView.getRView());

        mView.getSwip().setHeaderView(createHeaderView());
        mView.getSwip().setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

            @Override
            public void onRefresh() {
                mView.getSeachView().et_search.setText("");
                mView.getSeachView().et_search.clearFocus();

                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mView.getSwip().setRefreshing(false);
                        progressBar.setVisibility(View.GONE);
                        mPageIndex = 1;
                        isSearch = false;
                        if(isCollection){
                            getCollectionCleanerData();
                        }else{
                            getData();
                        }
                    }
                }, 1000);
            }

            @Override
            public void onPullDistance(int distance) {
                // pull distance
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });

        mView.getSeachView().setSearchWay(new SearchView.SearchWay<MyCleanersBean>() {
            @Override
            public List<MyCleanersBean> getSearchData() {
                return mrecords;
            }

            //监听输入内容变化
            @Override
            public boolean matchItem(MyCleanersBean myCleanersBean, String s) {
                Log.i(TAG,"getSeachView ==> text = "+s);
                //有内容时禁止上拉加载
                if(!"".equals(s)){
                    mView.getSwip().setRefreshing(false);
                    mView.getSwip().setLoadMore(false);
                }
                return true;
            }

            @Override
            public void update(List<MyCleanersBean> recordSearchResult) {

                //setData(true, recordSearchResult);
            }

            //点击搜索
            @Override
            public void search(String name) {
                //Log.i(TAG,"getSeachView ==> text = "+name);
                Params params = new Params();
                params.add("likeWrapper", name);
                params.add("limit", 1000);
                params.add("orderCode", mView.getOrderCode());
                params.add("page", 1);
                params.add("serviceTime", mView.getServiceTime());
                mAuz.auzpost(UrlPool.ORDER_MY_CLEANERS, params, new AuzImpl.AuzListener() {
                    @Override
                    public void AuzSuccess(int code, String data) {
                        if (code == 0) {
                            JSONObject obj = JSON.parseObject(data);
                            String str = obj.getString("records");
                            mTotalNum = obj.getInteger("total");
                            mrecordsFilter = JSON.parseArray(str, MyCleanersBean.class);
                            isSearch = true;

                            //计算骑行距离
                            //for (int i = 0; i < mrecordsFilter.size(); i++) {
                                //Log.i(TAG,"onRideRouteSearched ==>保洁员：" + mrecordsFilter.get(0).getRealName());
                            if (mrecordsFilter.size() > 0){
                                RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                                        new LatLonPoint(Double.valueOf(StateUtils.AddLat), Double.valueOf(StateUtils.AddLon)),
                                        new LatLonPoint(Double.valueOf(mrecordsFilter.get(0).getLat()), Double.valueOf(mrecordsFilter.get(0).getLon())));
                                RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(
                                        fromAndTo, RouteSearch.RIDING_DEFAULT);
                                mView.getRouteSearch().calculateRideRouteAsyn(query);
                            }else {
                                mAdapter.setEmptyView(mView.getViews());
                            }

                            //}
                            //setData(true, mrecordsFilter,false);

                        } else {
                            mView.onData();
                        }
                    }

                    @Override
                    public void AuzFailure(int errorCode, String msg) {
                        isErr = false;
                        mView.onFailure(errorCode, msg);
                    }
                });
            }
            //点击了清除按钮
            @Override
            public void clearText() {
                Log.i(TAG,"clearText()");
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {

                        mPageIndex = 1;
                        isSearch = false;
                        getData();
                    }
                }, 500);
            }
        });

    }


    private View createHeaderView() {
        View headerView = LayoutInflater.from(mView.getSwip().getContext())
                .inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.down_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    public void setData(boolean isRefresh, List data, boolean isSearch) {
        if (isSearch){
            mPageIndex++;
        }
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (data == null || data.size() == 0) {
                mNoData = false;
                mView.getSwip().setEnabled(false);
                mAdapter.setEmptyView(mView.getViews());
            } else {
                mView.getSwip().setEnabled(true);
                mAdapter.setNewData(data);
            }
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        mCurrentCounter = mAdapter.getData().size();
        if (size < mPageIndex) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }


    /**
     * 取消收藏保洁员
     */
    public void CancelCollectionCleaner(final int position){
        if (mLoadDialog == null){
            mLoadDialog = new LoadDialog(mContext, "");
        }
        mLoadDialog.show();
        Params params = new Params();
        params.add("cleanerCode",mrecords.get(position).getCleanerCode());//保洁员Code
        params.add("title","");
        mAuz.auzpost(UrlPool.POST_UNCOLLECTION_CLEANER, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    mLoadDialog.dismiss();
                    //mView.onSuccess(code, "取消收藏成功");
                    Toast.makeText(mContext, "取消收藏成功", Toast.LENGTH_LONG).show();
                    //mrecords.clear();
                    mrecords.remove(position);
                    mAdapter.notifyItemRemoved(position);
                    //必须调用这行代码
                    mAdapter.notifyItemRangeChanged(position, mrecords.size());
                    if(mrecords.size()== 0){
                        mAdapter.setEmptyView(mView.getViews());
                    }
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mLoadDialog.dismiss();
                //Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
                mView.onFailure(errorCode, msg);
            }
        });
    }

    /**
     * 收藏保洁员列表
     */
    public void getCollectionCleanerData() {
        Params params = new Params();
        params.add("limit", mView.getLimit());
        params.add("orderCode", mView.getOrderCode());
        params.add("page", mPageIndex);
        params.add("serviceTime", mView.getServiceTime());
        params.add("likeWrapper", "");
        Log.i(TAG,"getCollectionCleanerData ==> ");
        mAuz.auzpost(UrlPool.POST_OLLECTION_CLEANER_LIST, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    String str = obj.getString("records");
                    mTotalNum = obj.getInteger("total");
                    mrecords = JSON.parseArray(str, MyCleanersBean.class);

                    //计算骑行距离
                    //for (int i = 0; i < mrecords.size(); i++) {
                    Log.i(TAG,"onRideRouteSearched ==>0 收藏保洁员size：" + mrecords.size());
                    if(mrecords.size() > 0 ){
                        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                                new LatLonPoint(Double.valueOf(StateUtils.AddLat), Double.valueOf(StateUtils.AddLon)),
                                new LatLonPoint(Double.valueOf(mrecords.get(0).getLat()), Double.valueOf(mrecords.get(0).getLon())));
                        RouteSearch.RideRouteQuery query = new RouteSearch.RideRouteQuery(
                                fromAndTo, RouteSearch.RidingDefault);
                        mView.getRouteSearch().calculateRideRouteAsyn(query);
                    }else{
                        mAdapter.setEmptyView(mView.getViews());
                    }

                    //}

                    /*if (mPageIndex == 1) {
                        setData(true, mrecords,true);
                    } else {
                        setData(false, mrecords,true);
                    }*/
                } else {
                    mView.onData();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                isErr = false;
                mView.onFailure(errorCode, msg);
            }
        });
    }

    /**
     * 分享保洁员弹框
     */
    public void shareDialog(final int position){
        dialogshow=new ShareCleanerDialog(mContext,"");
        dialogshow.setTitleText("分享保洁员");
        dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {

                Log.i(TAG,"shareDialog ==> dialogshow.getContent = "+dialogshow.getContentText());
                shareCleaner(mrecords.get(position).getCleanerCode(),dialogshow.getContentText());
                dialogshow.dismiss();

            }
        });
        dialogshow.setImgAddBook(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                    mView.jumpContacts();
            }
        });
        dialogshow.setCancelable(false);
        dialogshow.show();


    }

    /**
     * 分享保洁员
     * @param cleanerCode
     * @param tell
     */
    private void shareCleaner(String cleanerCode, String tell){
        if (mLoadDialog == null){
            mLoadDialog = new LoadDialog(mContext, "");
        }
        mLoadDialog.show();
        Params params = new Params();
        params.add("tell", tell);
        params.add("cleanerCode", cleanerCode);
        mAuz.auzpost(UrlPool.POST_FOLLOW_SHARE, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    mLoadDialog.dismiss();
                    Toast.makeText(mContext, "分享成功", Toast.LENGTH_LONG).show();

                } else {
                    mView.onData();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                isErr = false;
                mLoadDialog.dismiss();
                mView.onFailure(errorCode, msg);
            }
        });
    }

}
